﻿/// <reference path="../jquery-1.11.3.min.js" />
/// <reference path="../layer/layer.js" />
/// <reference path="OpenLayers.js" />

var map, ais, layerS, layerS2, popup, as_control, as_control2, editbar, select;
var PATH_RADIUS = 0.00000001;

var vector = new OpenLayers.Layer.Vector("绘图", {
    styleMap: new OpenLayers.StyleMap({
        'default': {
            strokeColor: "#00FF00",
            strokeOpacity: 1,
            strokeWidth: 3,
            fillColor: "#FF5500",
            fillOpacity: 0.5,
            pointRadius: 10,
            pointerEvents: "visiblePainted",


            fontSize: "12px",
            fontFamily: "Courier New, monospace",
            fontWeight: "bold",
            labelAlign: "${align}",

            labelOutlineColor: "white",
            labelOutlineWidth: 3
        }
    })
});
var vector2 = new OpenLayers.Layer.Vector("VTS绘图", {
    styleMap: new OpenLayers.StyleMap({
        'default': {
            strokeColor: "#336699",
            strokeOpacity: 1,
            strokeWidth: 3,
            fillColor: "#005500",
            fillOpacity: 0.5,
            pointRadius: 10,
            pointerEvents: "visiblePainted",


            fontSize: "12px",
            fontFamily: "Courier New, monospace",
            fontWeight: "bold",
            labelAlign: "${align}",

            labelOutlineColor: "white",
            labelOutlineWidth: 3
        }
    })
});

editbar = new OpenLayers.Control.EditingToolbar(vector);
var options = {
    maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),
    projection: new OpenLayers.Projection("EPSG:4326"),
    displayProjection: new OpenLayers.Projection("EPSG:4326"),
    units: "degrees",
    //numZoomLevels:16,
    controls: [
        new OpenLayers.Control.Zoom(),
                    new OpenLayers.Control.LayerSwitcher(),
                    new OpenLayers.Control.Navigation(),
                    new OpenLayers.Control.ScaleLine(),
                    new OpenLayers.Control.SelectFeature(vector),
                    new OpenLayers.Control.MousePosition(),
                    editbar
    ],
    eventListeners: {
        "zoomend": showZoom
    }


};
function showZoom() {
    if (map.getScale() >= 55367980.3125) {
        map.setCenter(map.getCenter(), 2);
    }
    if (map.getZoom() < 11)
    { plonlat = null; }
    createRed(plonlat);
}
var layeroption={
    LAYERS: 'cyx:mobile_ship',
    transparent: "true",
    format: 'image/png'
    // ,CQL_FILTER:'company %27%27'
}
if(company){
    // company = 'eaea528f-c5ff-45b2-a52b-1681620036a4';
    layeroption.CQL_FILTER = "company_id='"+company+"'";
}

function init() {
    findDimensions();
    map = new OpenLayers.Map(document.getElementById("map"), options);
    map.div.oncontextmenu = function () { }//屏蔽右击菜单
    layer1 = new OpenLayers.Layer.WMS("基本", "http://map.zmsa.com.cn/map/myImage.ashx", { "styles": "base", "layers": "ENC", "format": "image/png" });
    layer2 = new OpenLayers.Layer.WMS("标准", "http://map.zmsa.com.cn/map/myImage.ashx", { "styles": "std", "layers": "ENC", "format": "image/png" });
    layer3 = new OpenLayers.Layer.WMS("全部", "http://map.zmsa.com.cn/map/myImage.ashx", { "styles": "all", "layers": "ENC", "format": "image/png" });
    layerT = new OpenLayers.Layer.XYZ("天地图", ["http://t0.tianditu.com/DataServer?T=vec_c&X=${x}&Y=${y}&L=${z}", "http://t1.tianditu.com/DataServer?T=vec_c&X=${x}&Y=${y}&L=${z}"], { isBaseLayer: true, displayInLayerSwitcher: true });
    layerS = new OpenLayers.Layer.WMS("船舶", "http://geo.zmsa.com.cn:8081/geoserver/cyx/wms",
        {
            LAYERS: 'cyx:ais_ship',
            transparent: "true",
            format: 'image/png'
        },
        {
            singleTile: true,
            ratio: 1,
            isBaseLayer: false,
            yx: { 'EPSG:4326': true },
            visibility: true,
            t: new Date()
        }
    ); //定义船舶图层

    layerS2 = new OpenLayers.Layer.WMS("船E行", "http://geo.zmsa.com.cn:8081/geoserver/cyx/wms",
        layeroption,
       {
           singleTile: true,
           ratio: 1,
           isBaseLayer: false,
           yx: { 'EPSG:4326': true },
           visibility: true,
           t: new Date()

       }
   ); //定义船舶图层

    if(!company){
        map.addLayers([layerT, layer1, layer2, layer3, layerS, layerS2, bkLayer, vector,vector2]); //图层
        // map.addLayer(layerS);
        getFeature();
        getVtsFeature();
    }else{
        map.addLayers([layerT, layer1, layer2, layer3,  layerS2, bkLayer, vector]); //图层
        //editbar.active = false;
        getServer();
        //getVtsFeature();
    }

    as_control = new OpenLayers.Control.DrawFeature(vector, OpenLayers.Handler.RegularPolygon, { handlerOptions: { sides: 4, irregular: true }, 'displayClass': 'olAreaBox', title: '区域查询', featureAdded: AreaShips }),

    editbar.addControls([as_control]);

    for (var i = 0; i < editbar.controls.length; i++) {

        if (editbar.controls[i].CLASS_NAME == "OpenLayers.Control.DrawFeature" && editbar.controls[i].displayClass != "olAreaBox") {
            //editbar.controls[i].events.register("featureadded", this, drawCompleted);
            editbar.controls[i].events.on({
                "featureadded": drawCompleted,
                "featuremodified": drawCompleted
            });
        }
    }

    //select参数
    var soptions = { //select 参数
        hover: false,
        onSelect: onFeatureSelect,
        onUnselect: onFeatureUnselect,
        clickout: true

    }
    select = new OpenLayers.Control.SelectFeature(vector, soptions);
    //select = new OpenLayers.Control.SelectFeature([vector2, vector], soptions);
    map.addControl(select);
    select.activate();

    map.events.register('click', map, getWFS);
    //infoControls.click.activate();
    map.setCenter(new OpenLayers.LonLat(118.8204, 32.15705), 13);

    getAis();
}


var onFeatureSelect = function (feature) {
    if (feature.source) {
        editFeatureVts(feature);
    }
    else
        editFeature(feature)
}

var editFeatureVts = function (feature) {
    var ft = feature.geometry.CLASS_NAME.split('.')[2];
    //console.log(feature.id);
    var info = "<tr><td class='tdl'>标题</td><td class='tdr'><input style='width:300px;' id='txtTitle' type='text' /></td><tr>";
    info += " </tr><td class='tdl'>内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
    info += " </tr><td class='tdl'>触发事件</td><td class='tdr'><select id='_event'><option value='1'>靠近</option>" + (ft == "Polygon" ? "<option value='2'>进入</option>" : "") + "</select></td></tr>";

    var ml = layer.open({
        id: 'addWarn',
        area: ['450px'],
        type: 1,
        closeBtn: 0,
        title: ["查看VTS警告", 'font-size:18px; font-weight:bold'],
        content: "<table class='detail'>" + info + "</table>",
        btn: ["关闭","无效","删除"],
        success: function () {
            $("#txtTitle").val(feature.properties.Title);
            $("#txtContent").val(feature.properties.Content);
            $("#_event").val(feature.properties.Event);
        },
        yes: function (index) {
            layer.close(ml);
            select.unselect(feature);
        },btn2:function(){
            $.ajax({
                type:'post',
                url:'/manage/map/setAlert',
                data:{guid:feature.id,state:'0'},
                dataType: "json",
                success:function(data){
                    if(data){
                        vector2.removeFeatures(feature);
                    }
                }
            });
        },btn3:function(){
            $.ajax({
                type:'post',
                url:'/manage/map/dropAlert',
                data:{guid:feature.id},
                dataType: "json",
                success:function(data){
                    if(data){
                        vector2.removeFeatures(feature);
                        //refreshAll();
                    }
                }
            });
        }
    })

}

/**
 * 获取VTS告警信息
 */
var getVtsFeature = function () {

    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        type: "POST",
        url: basePath + "manage/map/alertList",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = []; //
            for (i = 0; i < data.list.length; i++) {
                var f = ff.read(data.list[i].Geom);

                var pp = data.list[i];
                f.properties = pp;
                f.id = pp.Guid;
                f.source = 'vts';
                ffs.push(f);
            }
            vector2.addFeatures(ffs);
        }
    })
}


var onFeatureUnselect = function (feature) { }
var getWFS = function (e) {

    var shipLayers = "";
    if(layerS.getVisibility()){
        shipLayers = "cyx:ais_ship,cyx:mobile_ship";
    }else{
        shipLayers = "cyx:mobile_ship";
    }
    if(company){
        shipLayers = "cyx:mobile_ship";
    }

    if (map.getZoom() >= 1 && (layerS.visibility != false || layerS2.visibility != false)) {
        var params = {
            REQUEST: "GetFeatureInfo",
            BBOX: map.getExtent().toBBOX(),
            SERVICE: "WMS",
            INFO_FORMAT: 'application/json',
            QUERY_LAYERS: shipLayers,
            FEATURE_COUNT: 5,
            LAYERS: shipLayers,
            WIDTH: map.size.w,
            HEIGHT: map.size.h,
            format: 'image/png',
            styles: layerS.params.styles,
            srs: layerS.params.SRS
        };
        if (layerS.params.VERSION == "1.3.0") {
            params.version = "1.3.0";
            params.j = parseInt(e.xy.x);
            params.i = parseInt(e.xy.y);
        } else {
            params.version = "1.1.1";
            params.x = parseInt(e.xy.x);
            params.y = parseInt(e.xy.y);
        }

        var url = "/manage/map/navigat/warning/gf";
        if(company){
            url = "/manage/map/company/gf";
        }
        $.ajax({
            type: "GET",
            //url: "ashx/getFeatures.ashx",

            url: url,
            data: params,
            dataType: "json",
            success: function (data) {
                showInfo(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    }
}

function callback() { }

function receive() { }
var getAis = function () {
    clearTimeout(ais);
    ais = null;
    map.events.unregister("click", map, getWFS);
    map.events.register('click', map, getWFS);
    var OrCenter = map.getCenter();
    map.setCenter(new OpenLayers.LonLat(OrCenter.lon + PATH_RADIUS, OrCenter.lat), map.getZoom());
    map.setCenter(new OpenLayers.LonLat(OrCenter.lon - PATH_RADIUS, OrCenter.lat), map.getZoom());
    ais = setTimeout(getAis, 5000);
}

var showInfo = function (obj) {

    if (obj.features.length > 0) {
        var prop = obj.features[0].properties;

        var btn = [];
        if (prop.guid){
            btn = ['航次报告', '险情报告','发送信息'];
            if(!company){
                btn.push("报告线记录");
            }
        }




        //console.log(obj.features[0]);
        var shipname = (prop.shipname == null ? "暂无" : prop.shipname);
        var shipid = (prop.shipid == null ? "" : prop.shipid);
        var iemi = (prop.shipimei == null ? "" : prop.shipimei);
        //info = '<div class="detail" ><ul><li>船名:<a id=\"cm\" class=\"copy-button\" href=\"#\">' + (shipname) + '</a><a class=\"btn_xx\" style=\" text-decoration:underline; color:blue;\" ob=\"' + prop.mmsi + '\" href=\"#\" >(详细信息)</a></li><li>MMSI:<a class=\"copy-button\" href=\"#\">' + prop.mmsi + '</a></li><li>当前经度:<a class=\"copy-button\" href=\"#\">' + SetHMS(prop.lon) + '</a></li><li>当前纬度:<a class=\"copy-button\" href=\"#\">' + SetHMS(prop.lat) + '</a></li><li>速度:' + prop.speed + '</li><li>航向:' + prop.course + '</li><li>最新时间:' + prop.postime + '</li></ul></div>';
        var info = "";
        //info = "<tr><td class='tdl'>船名</td><td class='tdr'>" + shipname + "</td></tr>";
        info += "<tr><td class='tdl'>MMSI</td><td class='tdr'>" + prop.mmsi + "</td></tr>";
        info += "<tr><td class='tdl'>经度</td><td class='tdr'>" + SetHMS(prop.lon) + "</td></tr>";
        info += "<tr><td class='tdl'>纬度</td><td class='tdr'>" + SetHMS(prop.lat) + "</td></tr>";
        info += "<tr><td class='tdl'>速度</td><td class='tdr'>" + prop.speed + "</td></tr>";
        info += "<tr><td class='tdl'>航向</td><td class='tdr'>" + prop.course + "</td></tr>";
        info += "<tr><td class='tdl'>时间</td><td class='tdr'>" + prop.postime + "</td></tr>";
        layer.open({
            id: 'showdiv',
            type: 1,
            area: '500px',
            closeBtn: 1,
            title: [shipname, 'font-size:18px; font-weight:bold'],
            content: "<table class='detail'>" + info + "</table>",
            end: function () { bkLayer.removeAllFeatures(); plonlat = null; },
            btn: btn
                , yes: function (index, layero) {
                if(company){
                    showhtml(basePath+'/manage/map/company/voyage?shipid='+shipid, shipname+"航次报告");
                }else{
                    showhtml(basePath+'/manage/map/voyage?shipid='+shipid, shipname+"航次报告");
                }
                    
                }, btn2: function (index, layero) {
                     if(company){
                         showhtml(basePath+'/manage/map/company/accident?shipid='+shipid, shipname+"险情报告");
                     }else{
                         showhtml(basePath+'/manage/map/accident?shipid='+shipid, shipname+"险情报告");
                     }
                    return false;
                }, btn3: function (index, layero) {
                sendMessage(shipid,"向"+shipname+"发送消息");
                },btn4 : function () {
                if(company){
                    showhtml(basePath+"manage/map/company/touchLine?shipid="+shipid+"&iemi="+iemi, shipname+"报告线记录");
                }else{
                    showhtml(basePath+"manage/map/touchLine?shipid="+shipid+"&iemi="+iemi, shipname+"报告线记录");
                }

                return false;
            }
        });
        plonlat = new OpenLayers.LonLat(prop.lon, prop.lat);


        createRed(plonlat);
        //showPopup(plonlat, info);

    }

}
var showhtml = function (url, title) {

    layer.open({
        id: 'showcontent',
        area: ['970px', '440px'],
        type: 2,
        closeBtn: 1,
        title: [title, 'font-size:18px; font-weight:bold'],
        content: url

    })
}
var showPopup = function (plonlat, info) {
    if (popup != null) {
        map.removePopup(popup);
        popup = null;
    }
    popup = new OpenLayers.Popup.FramedCloud("chicken", plonlat, null, info, null, true, onPopupClose);
    map.addPopup(popup);

}
var onPopupClose = function () {
    map.removePopup(popup);
    bkLayer.removeAllFeatures();
    plonlat = null;

}
var AreaShips = function (e) {

    var parm = e.geometry.bounds.toBBOX();
    //console.log(layerS.visibility);
    var ft = "";
    // if (layerS.visibility != false)
    // ft.push("ais_ship");
    if (layerS2.visibility != false)
        ft="mobile_ship";

    $.ajax({
        type: "POST",
        url: "/manage/map/navigat/warning/getFeatureByBbox.ashx",
        data: { bbox: parm, ft: ft },
        dataType: "text",
        success: function (data) {
            //console.log(data);
            var format = new OpenLayers.Format.GML.v3({
                featureNS: "cyx",
                featurePrefix: "cyx",
                featureType: ft,//["mobile_ship", "ais_ship"],
                layerName: "cyx",
                geometryName: "geom",
                srsName: "EPSG:4326",
                version: "1.1.0"
            });
            var list = format.read(data);
            var ships = [];
            var s = "";
            //console.log(list);
            for (var i = 0; i < list.length; i++) {
                s += "<div class='d_block'>" + (list[i].data.shipname == null ? "" : list[i].data.shipname) + "(" + list[i].data.mmsi + ")</div>";
                ships.push(list[i].data.shipid);
            }

            if (s != "") {
                //var _cp = e.geometry.getCentroid();
                //var _lonlat = new OpenLayers.LonLat(_cp.x, _cp.y);

                //showPopup(_lonlat, "<div class=\"detail\" >" + s + "</div>");
                layer.open({
                    id: 'showdiv',
                    type: 1,
                    area: '500px',
                    closeBtn: 1,
                    title: ["区域查询结果", 'font-size:18px; font-weight:bold'],
                    content: "<div class='detail'>" + s + "</div>",
                    //end: function () { bkLayer.removeAllFeatures(); plonlat = null; },
                    btn: ['群发消息', '关闭']
               , yes: function (index, layero) {
                        sendMessage(ships);
               }, btn2: function (index, layero) {

               }
                });
            }
            else {
                layer.msg("当前区域无船E行相关船舶");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });

    vector.removeFeatures(e);
}

function serialize(feature) {
    try {
        var pretty = true;
        var str = new OpenLayers.Format.WKT().write(feature, pretty).replace(/,/g, ', '); //formats['out'][type].write(feature, pretty);
        return str;
    } catch (e) {
        return "";
    }

}
function type() {
    var str = "";
    $.ajax({
        type: "POST",
        async:false,
        url: "/manage/map/type/selecttype",
        data: {},
        dataType: "json",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                str = str + "<option value='" + data[i].typevalue + "'>" + data[i].typetext + "</option>";
            }
        }
    });
    return str;
}

function deserialize(v, layer) {

    var features = new OpenLayers.Format.WKT().read(v);
    var bounds;
    if (features) {
        if (features.constructor != Array) {
            features = [features];
        }
        for (var i = 0; i < features.length; ++i) {
            if (!bounds) {
                bounds = features[i].geometry.getBounds();
            } else {
                bounds.extend(features[i].geometry.getBounds());
            }

        }
        layer.addFeatures(features);
        var plural = (features.length > 1) ? 's' : '';

    } else {
        alert("格式错误");
    }
}
function shipway(chk) {
    if(chk.checked){
        document.getElementById("lat").style.display = "none";
        document.getElementById("lon").style.display = "none";
        document.getElementById("shipmmsi").style.display = "block";
    }
}
function show1(chk) {
    if(chk.checked){
        document.getElementById("lat").style.display = "block";
        document.getElementById("lon").style.display = "block";
        document.getElementById("shipmmsi").style.display = "none";
    }

}


//绘图
var drawCompleted = function (e) {
    editFeature(e.feature);
}

var editFeature = function (feature) {
    if (!company) {
        var ft = feature.geometry.CLASS_NAME.split('.')[2];
        var info = "<tr><td class='tdl'>标题</td><td class='tdr'><input style='width:300px;' id='txtTitle' type='text' /></td><tr>";
        info += " </tr><td class='tdl'>内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
        info += " </tr><td class='tdl'>触发事件</td><td class='tdr'><select id='_event'><option value='1'>靠近</option>" + (ft == "Polygon" ? "<option value='2'>进入</option>" : "") + "</select></td></tr>";
        var guid = "";
        var btn = ['保存', '取消'];
        if (feature.properties && feature.properties.guid) {
            guid = feature.properties.guid;
            btn = ['保存', '取消', '删除'];
        }
    } else {
        var ss = "";
        ss = type();
        var ft = feature.geometry.CLASS_NAME.split('.')[2];
        var info = "<tr><td class='tdl'>服务类型</td><td class='tdr'><select name='selectserver' id='selectserver'>" +
                ss +
            "</select></td><tr>" ;
        info += "</tr><td class='tdl'>服务方式</td><td class='tdr'><input name='way' id='baseway' type='radio' checked='checked' value='地点' onclick='show1(this)'/>地点<input name='way' id='shipway' type='radio' value='船舶' onclick='shipway(this)'/>船舶</td><br>"
        info += "</tr><td class='tdl'>请输入</td><td class='tdr'><input type='text' style='display: none;width:100px;' id='shipmmsi' placeholder='MMSI' ><input type='text' style='width:100px;' id='lon' placeholder='经度'><input type='text' style='width:100px;float: left' id='lat' placeholder='纬度'></td> "
        info += "</tr><td class='tdl'>关键字</td><td class='tdr'><input style='width:300px;' id='keyword' type='text' placeholder='逗号隔开，最多五个字符，最多三个'/></td>"
        info += "</tr><td class='tdl'>服务内容</td><td class='tdr'><textarea style='width:300px;' id='txtContent' rows='5' ></textarea></td></tr>";
        var ssid = "";
        var btn = ['发布', '取消'];
        if (feature.properties && feature.properties.ssid) {
            ssid = feature.properties.ssid;
            btn = ['发布', '取消', '删除'];
        }

    }if(!company){
        var ml = layer.open({
            id: 'addWarn',
            area: ['450px'],
            type: 1,
            closeBtn: 0,
            title: ["保存警告", 'font-size:18px; font-weight:bold'],
            content: "<table class='detail'>" + info + "</table>",
            btn: btn,
            success: function () {
                if (guid && guid != "") {

                    $("#txtTitle").val(feature.properties.title);
                    $("#txtContent").val(feature.properties.contents);
                    $("#_event").val(feature.properties.event);

                }
            },
            yes: function (index) {

                var title = $("#txtTitle").val();
                var content = $("#txtContent").val();
                var _event = $("#_event").val();
                if (title == "" || content == "") {
                    layer.msg("标题和内容不能为空");
                }
                else {
                    var prop = {
                        guid: guid,
                        title: title,
                        contents: content,
                        wkt: serialize(feature),
                        warningtype: ft,
                        event: _event,
                        mark: ""
                    }
                    feature.properties = prop;
                    $.ajax({
                        type: "POST",
                        url: "/manage/map/navigat/warning/save",
                        data: prop,
                        dataType: "json",
                        success: function (data) {
                            if (data.result == true) {
                                feature.properties.guid = data.guid;
                                feature.id = data.guid;
                                layer.close(ml);
                                layer.msg("保存成功");
                                select.unselect(feature);
                            }
                            else {
                                layer.msg("保存失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                }
            },
            btn2: function (index) {
                if (guid == "") {
                    vector.removeFeatures(feature);
                }
                else {
                    select.unselect(feature);
                }
            },
            btn3: function (index) {
                select.unselect(feature);
                layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/manage/map/navigat/warning/delete",
                        data: {guid: guid, action: "d"},
                        dataType: "json",
                        success: function (data) {
                            if (data.result == true) {
                                vector.removeFeatures(feature);
                                layer.msg("删除成功");
                                layer.close(ml);
                            }
                            else {
                                layer.msg("保存失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                });
            }
        })}else {
        var ml = layer.open({
            id: 'addServer',
            area: ['450px'],
            type: 1,
            closeBtn: 0,
            title: ["服务信息", 'font-size:18px; font-weight:bold'],
            content: "<table class='detail'>" + info + "</table>",
            btn: btn,
            success: function () {
                if (ssid && ssid != "") {
                    //alert($("#selectserver").val(3));
                    var rr = (feature.properties.serverway).toString();
                    var ss = (feature.properties.serverType).toString();
                    //alert(ss);
                    if(rr == "地点"){
                        document.getElementById("lat").style.display = "block";
                        document.getElementById("lon").style.display = "block";
                        document.getElementById("shipmmsi").style.display = "none";
                    }else if(rr == "船舶"){
                        document.getElementById("lat").style.display = "none";
                        document.getElementById("lon").style.display = "none";
                        document.getElementById("shipmmsi").style.display = "block";
                    }
                    $("#selectserver option:contains('"+ss+"')").attr("selected", true);
                    $("#selectserver").find("option[text=ss]").attr("selected",true);
                    $("input[name='way'][value='"+rr+"']").attr("checked",true);
                    $("#keyword").val(feature.properties.keyword);
                    $("#txtContent").val(feature.properties.message);
                    $("#lon").val(feature.properties.lon);
                    $("#lat").val(feature.properties.lat);
                    $("#shipmmsi").val(feature.properties.mmsi);

                }
            },
            yes: function (index) {

                var serverType = $("#selectserver").find("option:selected").text();
                var keyword = $("#keyword").val();
                var message = $("#txtContent").val();
                var serverway = $("input[name='way']:checked").val();
                var lon = $("#lon").val();
                var lat = $("#lat").val();
                var mmsi = $("#shipmmsi").val();
                if (serverType == "" || message == "" || serverType == "==请选择==") {
                    layer.msg("类型和内容不能为空");
                }else{
                    var prop = {
                        ssid:ssid,
                        serverType: serverType,
                        wkt: serialize(feature),
                        keyword:keyword,
                        message: message,
                        serverway:serverway,
                        lon:lon,
                        lat:lat,
                        mmsi:mmsi,
                    }
                    feature.properties = prop;
                    $.ajax({
                        type: "POST",
                        url: "/manage/map/server/saveserver",
                        data: prop,
                        dataType: "json",
                        success: function (data) {
                            //alert("zzz");
                            if (data.result == true) {
                                feature.properties.ssid = data.ssid;
                                feature.id = data.ssid;
                                layer.close(ml);
                                layer.msg("发布成功");
                                select.unselect(feature);
                            }
                            else if(data.keyword == false){
                                layer.msg("关键字过长");
                            }else if(data.mmsi == false){
                                layer.msg("无效的mmsi");
                            }else if(data.latlon == false){
                                layer.msg("经纬度不可为空");
                            }
                            else {
                                layer.msg("发布失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                }
            },
            btn2: function (index) {
                if (ssid == "") {
                    vector.removeFeatures(feature);
                }
                else {
                    select.unselect(feature);
                }
            },
            btn3: function (index) {
                select.unselect(feature);
                layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/manage/map/server/delete",
                        data: {ssid: ssid, action: "d"},
                        dataType: "json",
                        success: function (data) {
                            if (data.result == true) {
                                vector.removeFeatures(feature);
                                layer.msg("删除成功");
                                layer.close(ml);
                            }
                            else {
                                layer.msg("发布失败");
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                });
            }
        })
    }

    }


var getServer = function () {

    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/server/ajax/data/list",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (i = 0; i < data.length; i++) {
                var f = ff.read(data[i].wkt);
                var pp = data[i];
                f.properties = pp;
                f.id = pp.ssid;
                ffs.push(f);
            }
            vector.addFeatures(ffs);

        }
    })
}

var getFeature = function () {

    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        type: "POST",
        url: "/manage/map/navigat/warning/ajax/data/list",
        data: {},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            for (i = 0; i < data.length; i++) {
                var f = ff.read(data[i].wkt);
                //alert(data[i].wkt);
                var pp = data[i];
                f.properties = pp;
                f.id = pp.guid;
                ffs.push(f);
            }
            vector.addFeatures(ffs);

        }
    })
}


var my_Position = function (a) {

    var tmp = vector.getFeatureById(a);
    if (tmp != null) {
        var lonlat = tmp.geometry.getBounds().getCenterLonLat();
        map.setCenter(lonlat, map.getZoom());
        showPopup(lonlat, tmp.properties.title);
    }
    else {
        layer.msg("未找到相关元素");
    }
}

/**
 * 定位船舶, a lon  b lat c 船舶名称
 * @param a
 * @param b
 * @param c
 */
var positionShip = function (a, b,c) {
    var lonlat = new OpenLayers.LonLat(a,b);
    map.setCenter(lonlat, map.getZoom());
    showPopup(lonlat, c);
};

var hideWaters = function(a,b,c){
    var lonlat = new OpenLayers.LonLat(a,b);
    map.setCenter(lonlat, map.getZoom());
    hidePopup(lonlat,c);
}
var sendMessage = function (ships,title) {
    if(typeof ships == "array"){
        ships = ships.join()
    }
    if(title == null){
        title = "发送消息";
    }
    var url = basePath+'/manage/map/message?ships='+ships ;
    if(company){
        url = basePath+'/manage/map/company/message?ships='+ships
    }
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0,
        maxmin: true,
        area: ['970px', '640px'],
        content:url //iframe的url
    });
}
/**
 * 显示水域（报告线）位置
 * @param a 经度
 * @param b 纬度
 * @param c 名称
 */
var showPosition = function (a, b,c) {
    var lonlat = new OpenLayers.LonLat(a,b);
    map.setCenter(lonlat, map.getZoom());
    showPopup(lonlat, c);
};


var hidePopup = function (plonlat, info) {
    if (popup != null) {
        map.removePopup(popup);
        popup = null;
    }
    /*popup = new OpenLayers.Popup.FramedCloud("chicken", plonlat, null, info, null, true, onPopupClose);
    map.addPopup(popup);*/
}
/**
 * 显示水域
 * @param data 水域ID
 */
var setPolygon = function(data){
    getWatersinfo(data);
}
/**
 * 显示报告线
 * @param lineId 报告线ID
 */
var setLine = function(lineId){
    showReportLine(lineId);
}

var showVtsInfo =function(id){
    findVts(id);
}

var findVts = function(guid){
    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        url: "/manage/map/oneVTS",
        data: {guid:guid},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  vector2.getFeatureById(data.Guid);
            if(fid==null){
                var f = ff.read(data.Geom);
                var pp = data;
                f.properties = pp;
                f.id = pp.Guid;
                ffs.push(f);
                vector2.addFeatures(ffs);
            }
        }
    })
}

var showReportLine = function (id) {
    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        url: "/manage/reportline/info/one",
        data: {id:id},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  vector.getFeatureById(data.id);
            if(fid==null){
                var f = ff.read(data.coordinate);
                var pp = data;
                f.properties = pp;
                f.id = pp.id;
                ffs.push(f);
                vector.addFeatures(ffs);
            }
        }
    })
}
/**
 * 显示水域信息
 * @param id
 */
var  getWatersinfo = function (id) {
    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        url: "/manage/waters/info/getWkt",
        data: {id:id},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  vector.getFeatureById(data.id);
            if(fid==null){
                var f = ff.read(data.coordinate);
                var pp = data;
                f.properties = pp;
                f.id = pp.id;
                ffs.push(f);
                vector.addFeatures(ffs);
            }
        }
    })
}
/**
 * 显示报告线
 * @param id 报告线ID
 */
var showReportLine = function (id) {
    var ff = new OpenLayers.Format.WKT();
    $.ajax({
        url: "/manage/reportline/info/one",
        data: {id:id},
        dataType: "json",
        success: function (data) {
            var ffs = [];
            var fid =  vector.getFeatureById(data.id);
            if(fid==null){
                var f = ff.read(data.coordinate);
                var pp = data;
                f.properties = pp;
                f.id = pp.id;
                ffs.push(f);
                vector.addFeatures(ffs);
            }
        }
    })
}

/**
 * 删除水域信息
 * @param id
 */
var romoveFeature = function(id){
    var fid =  vector.getFeatureById(id);
    vector.removeFeatures(fid);
}

var refreshAll = function(guid){
    var fid =  vector2.getFeatureById(guid);
    vector2.removeFeatures(fid);
    getVtsFeature();
}




